<!-- 箭头跟随鼠标转动 -->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>箭头跟随鼠标转动</title>
</head>

<body>
    <canvas id="canvas"></canvas>
</body>
<script src="../utils.js"></script>
<script>
    // 画三角类
    class Arrow {
        // 初始化配置信息
        constructor(options) {
            this.x = 0;  // 绘制位置
            this.y = 0;
            // 箭头大小
            this.w = 120;
            this.h = 60;
            this.rotation = 0; // 旋转角度
            this.fillColor = '#00000'; // 填充颜色
            this.strokeColor = '#00000'; // 描边颜色

            // 配置信息
            Object.assign(this, options);
            return this;
        }
        // 路径绘制
        createPath(ctx) {
            let { w, h } = this;
            // 开始新路径绘制
            ctx.beginPath();
            ctx.moveTo(-w / 2, -h / 2);
            ctx.lineTo(-w / 2, h / 2);
            ctx.lineTo(w / 10, h / 2);
            ctx.lineTo(w / 10, h);
            ctx.lineTo(w / 2, 0);
            ctx.lineTo(w / 10, -h);
            ctx.lineTo(w / 10, -h / 2);
            ctx.closePath();
            return this;
        }
        // 渲染
        render(ctx) {
            let { x, y, w, h, rotation, fillColor, strokeColor } = this;
            ctx.save();
            // 设置填充颜色
            ctx.fillStyle = fillColor;
            // 设置描边颜色
            ctx.strokeStyle = strokeColor;
            // 设置绘制位置 ,需要先移动位置再去调整角度，不然旋转角度会改变位置
            ctx.translate(x, y);
            // 设置旋转角度
            ctx.rotate(rotation);

            // 绘制路径
            this.createPath(ctx);
            ctx.fill(); // 填充
            ctx.stroke(); // 描边
            ctx.restore();
            return this;
        }

    }

    // 获取上下文  绘制
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    let w = canvas.width = 500;
    let h = canvas.height = 500;
    let mouse = c.getOffset(canvas);

    const arrow = new Arrow({
        x: w / 2,
        y: h / 2,
        w: 120,
        h: 60,
    }).render(ctx);

    canvas.addEventListener('mousemove', function (e) {
        let dx = mouse.x - arrow.x;
        let dy = mouse.y - arrow.y;
        arrow.rotation = Math.atan2(dy, dx);

        ctx.clearRect(0, 0, w, h);
        arrow.render(ctx);
    });
</script>

</html>